#!/usr/bin/python
import os
import sys
import MySQLdb
import string
import time
import cloud
import string
import db

def isDigtal(Num):
    nums = string.digits
    myNum = str(Num)
    if type(myNum) is not str:
        return False
    else:
        for temp in myNum:
            if temp not in nums:
                return False
        return True
        
def checkGetVmPara(conn,mtid,stid,sncnt):
  try:
    if not conn:
        #print "Can not connect to database, Fail!"
        return -1
    if not isDigtal(mtid):
        return -2
    if not isDigtal(stid):
        return -2
    if not isDigtal(sncnt):
        return -2
    flag,rows = db.exeFetchCommand(conn,"select vm_id from vm_info where vm_id = " + str(mtid));
    if flag == 0:
        #print "No Master Node VM ", mtid 
        return -2
    flag,rows = db.exeFetchCommand(conn,"select vm_id from vm_info where vm_id = " + str(stid));
    if flag == 0:
        #print "No Salve Node VM ", stid
        return -2
    return 1
  except:
    # execption
    return -5

def getVmForMpi(mtid,stid,sncnt):    
    try:  
        connect=db.connectDB()
        conn=db.cursorDB(connect)
        cnt, rows = db.exeFetchCommand(conn,"select mem,cpu,img_store_path from vm_info where vm_id = "+str(mtid)) 
        m_mem=int(rows[0][0])
        m_vcpu=int(rows[0][1])
        m_img_path=rows[0][2]

        cnt, rows = db.exeFetchCommand(conn,"select mem,cpu,img_store_path from vm_info where vm_id = "+str(stid))
        s_mem=int(rows[0][0])
        s_vcpu=int(rows[0][1])
        s_img_path=rows[0][2]
        
        db.closeCursor(conn)
        db.closeConnect(connect)
        
        #HVM={ 'memory':'512','vcpu':'2','img':'/srv/cloud/images/rhel5_x86_64_base.img','count':2 }
        #ret=cloudapi.create_vm(HVM)
        HVM_MASTER={ 'memory':str(m_mem),'vcpu':str(m_vcpu),'img':m_img_path,'count':1 }
        HVM_SALVE={ 'memory':str(s_mem),'vcpu':str(s_vcpu),'img':s_img_path,'count':sncnt }   
        #print HVM_MASTER
        #print HVM_SALVE 
        ret_m=cloud.create_vm(HVM_MASTER)
        ret_m_len = len(ret_m)
        if ret_m_len != 1:
            for tmp in ret_s_len:
                cloud.del_vm(tmp[0])
            return -3

        ret_s=cloud.create_vm(HVM_SALVE)
    
        ret_s_len = len(ret_s)
        if ret_s_len != sncnt:
            for tmp in ret_s_len:
                cloud.del_vm(tmp[0])
            return -3
	#ret_m=[['29', '192.168.100.129']]
        #ret_s=[['30', '192.168.100.130'], ['31', '192.168.100.131']] 
        #print ret_m 
        #print ret_s
        connect=db.connectDB()
        conn=db.cursorDB(connect)
        tmp=str(time.time()).split('.')
        startTime=str(tmp[0])
        cnt = db.exeSetCommand(conn,"insert into mpi_env(status,start_time,end_time) values('running',"+startTime+",0)")
        cnt,rows = db.exeFetchCommand(conn,"select max(env_id) from mpi_env")    
        env_id=rows[0][0]
    
        db.exeSetCommand(conn,"insert into env_resource(env_id,vm_id,vm_uid,vm_ip,vm_type) values("+str(env_id)+","+str(mtid)+","+str(ret_m[0][0])+",'" +str(ret_m[0][1])+"','master')")
    
        for tmp in ret_s:
            db.exeSetCommand(conn,"insert into env_resource(env_id,vm_id,vm_uid,vm_ip,vm_type) values("+str(env_id)+","+str(stid)+","+str(tmp[0])+",'" +str(tmp[1])+"','salve')")

        db.closeCursor(conn)
        db.closeConnect(conn)
        #print "Job ID ", env_id    
        return env_id
    except:
        #exception
        return -5

## Create Job ###
def create(mtid,stid,sncnt):
    try:  
        connect=db.connectDB()
        conn=db.cursorDB(connect)
        flag = checkGetVmPara(conn,mtid,stid,sncnt)
        db.closeCursor(conn)
        db.closeConnect(connect)
        # flag = -2: Parameter error.
        # flag = -1: Database connection failed.
        # flag = -5: exception
        if flag < 0:
            return flag
    
        flag = getVmForMpi(mtid,stid,sncnt)
        # flag = -3: IaaS start VM fail.
        # flag > 0: successful, return job_id
        return flag
    except:
        #exception
        return -5


